package com.bootssm.service.impl;

import com.bootssm.dao.BookMapper;
import com.bootssm.dao.BorrowMapper;
import com.bootssm.pojo.Borrow;
import com.bootssm.pojo.BorrowVO;
import com.bootssm.service.BorrowService;
import com.bootssm.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {
    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private IdWorker idWorker;

    @Override
    public List<Borrow> findAll(BorrowVO borrowVO) {
        Integer start = (borrowVO.getPage() - 1) * borrowVO.getPageSize();
        borrowVO.setPage(start);
        return borrowMapper.findAll(borrowVO);
    }

    @Override
    public Integer getTotal(BorrowVO borrowVO) {
        return borrowMapper.getTotal(borrowVO);
    }

    @Override
    public void update(Borrow borrow) {
        // 审核不通过
        if(borrow.getStatus() == 2) {
            // 图书库存+1
            bookMapper.addBookInventory(borrow.getBookId());
        }
        // 审核通过
        borrowMapper.update(borrow);
    }

    @Override
    public void insert(Borrow borrow) {
        // 1.保存到借阅申请表
        borrow.setBorrowId(idWorker.nextId() + "");
        borrowMapper.insert(borrow);

        // 2.让图书库存减1
        String bookId = borrow.getBookId();
        bookMapper.updateBookInventory(bookId);
    }

    @Override
    public void deleteById(Borrow borrow) {
        //1.取消申请
        borrowMapper.deleteById(borrow);

        //2.让图书库存+1
        bookMapper.addBookInventory(borrow.getBookId());
    }
}
